package com.unohacha.qqj.fzdr.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.widget.common.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.AfterPubAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.SupplyMatchModel;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.CommonSDActivity;
import com.unohacha.qqj.fzdr.main.FindDetailActivity2;
import com.unohacha.qqj.fzdr.main.LookBigPicActivity;
import com.unohacha.qqj.fzdr.main.LookMoreInfoActivity;
import com.unohacha.qqj.fzdr.ui.activity.AfterPubMatchActivity;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.FilterPopwindow;
import com.unohacha.qqj.mylibrary.base.BaseFragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

/**
 * 发布后匹配碎片
 */
public class AfterPubMatchFragment extends BaseFragment implements OnRefreshLoadmoreListener {

    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;

    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private FilterPopwindow filterPopwindow;//筛选弹窗
    private AfterPubMatchActivity mActivity;
    private int last_page = 1;//最大页数
    private String type = "0";//类型
    private List<SupplyMatchModel.DataBeanX.DataBean> pubMatchData;
    private int page = 1;//当前页数
    private String address_id = "12685";//定位后的或者选择后的地址id ,默认先写余杭区
    private String keywors = "";//关键词
    private BaseRVAdapter mBaseAdapter;
    private int supply_cate_id;//标签的id
    AfterPubAdapter afterPubAdapter;
    private int mNextRequestPage = 1;
    private static final int PAGE_SIZE = 10;
    private String orderId;
    @Override
    protected void initBundle(Bundle arguments) {
        type=arguments.getString("type");
        orderId=arguments.getString("orderId");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pub_fater;
    }

    @Override
    protected void initView(View rootView) {
        mActivity = (AfterPubMatchActivity) getActivity();

        if (!TextUtils.isEmpty(Prefer.getInstance().obtainReLocation(getContext()))){
            address_id = Prefer.getInstance().obtainReLocation(getContext());
        }else {
            address_id = "12685";//定位后的或者选择后的地址id ,默认先写余杭区
        }
        initTabLayout();
    }

    private void initTabLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));
        pubMatchData=new ArrayList<>();
        afterPubAdapter=new AfterPubAdapter(pubMatchData);
        carListRecycler.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayout.VERTICAL,false));

        carListRecycler.setAdapter(afterPubAdapter);
        getDefaultFind();

        afterPubAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //查看更多
                Intent intent = new Intent(getActivity(), LookMoreInfoActivity.class);
                intent.putExtra("member_id", afterPubAdapter.getData().get(position).getMember_id());
                intent.putExtra("one_pid", afterPubAdapter.getData().get(position).getOne_pid());
                intent.putExtra("supply_cate_id", afterPubAdapter.getData().get(position).getSupply_cate_id());
                intent.putExtra("typeid", Integer.valueOf(Prefer.getInstance().getKeyType()));
                intent.putExtra("matchToLook", 10000);
                intent.putExtra("order", orderId);
                intent.putExtra("ptype", type);
                startActivity(intent);
            }
        });

        afterPubAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), FindDetailActivity2.class);
                intent.putExtra("typeid", afterPubAdapter.getData().get(position).getOne_pid());
                intent.putExtra("address_id", address_id);
                intent.putExtra("id", afterPubAdapter.getData().get(position).getId());
                startActivity(intent);
            }
        });
    }

    @Override
    protected void initData() {

    }


    @OnClick({})
    public void onViewClicked(View view) {

        switch (view.getId()) {


        }
    }

    //默认是供应还是需求
    private void getDefaultFind(){
        Map<String, Object> stringMap = new HashMap<>();
        stringMap.put("token", Prefer.getInstance().getToken());
        stringMap.put("order",orderId);
        stringMap.put("ptype",type);
        stringMap.put("more","0");
        stringMap.put("page",page);

        XUtil.Post(UrlConfig.SUPPLY_MATCHING, stringMap, new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadmore();
                }

                try {
                    SupplyMatchModel supplyMatchModel = new SupplyMatchModel().toBean(result);
                    if (supplyMatchModel.getCode() == 1) {
                        setData(true,supplyMatchModel.getData().getData());
                    }else if (supplyMatchModel.getCode()==100){
                        mActivity.MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        ToastUtil.showCustomToast(supplyMatchModel.getMessage());
                        if (page == 1){
                            if (null != pubMatchData){
                                pubMatchData.clear();
                            }
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            //    mBaseAdapter.notifyDataSetChanged();
                        }else {
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                if (mRefreshLayout != null) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadmore();
                }
            }
        });
    }

    private void setData(boolean isRefresh,List<SupplyMatchModel.DataBeanX.DataBean> progect) {

        mNextRequestPage++;
        if (progect == null || progect.size() == 0) {
            return;
        }
        final int size = progect == null ? 0 : progect.size();
        if (isRefresh) {
            afterPubAdapter.setNewData(progect);
        } else {
            if (size > 0) {
                afterPubAdapter.addData(progect);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            afterPubAdapter.loadMoreEnd(isRefresh);
            //   Toast.makeText(this, "no more data", Toast.LENGTH_SHORT).show();
        } else {
            afterPubAdapter.loadMoreComplete();
        }
    }
    //设置发现列表的数据
    private void setFindApapter(){

        mBaseAdapter = new BaseRVAdapter(mActivity,pubMatchData) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_find_need_or_supply;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                final int tagPosition = position;
                RelativeLayout rl_user = holder.getView(R.id.rl_user);
                ImageView store_logo_iv = holder.getImageView(R.id.store_logo_iv);//头像
                TextView store_name_tv = holder.getTextView(R.id.store_name_tv);//名字
                TextView store_report_content = holder.getTextView(R.id.store_report_content);//发表的内容
                TextView report_time_tv = holder.getTextView(R.id.report_time_tv);//发表的时间
                TextView look_num_tv = holder.getTextView(R.id.look_num_tv);//浏览的数量
                TextView comment_num_tv = holder.getTextView(R.id.comment_num_tv);//评论的数量
                TextView collect_num_tv = holder.getTextView(R.id.collect_num_tv);//收藏的数量
                TextView get_message_tv = holder.getTextView(R.id.get_message_tv);//获取信息
                LinearLayout user_a_ll = holder.getView(R.id.user_a_ll);//用户a
                LinearLayout user_b_ll = holder.getView(R.id.user_b_ll);//用户b
                TextView user_a = holder.getTextView(R.id.user_a);//用户a姓名
                TextView user_comment_a = holder.getTextView(R.id.user_comment_a);//用户a 评论
                TextView user_b = holder.getTextView(R.id.user_b);//用户b姓名
                TextView user_comment_b = holder.getTextView(R.id.user_comment_b);//用户b 评论

                get_message_tv.setVisibility(View.GONE);
//                List<FindListBean.DataEntity.DataTwo.SupplyData> mSupplyList = new ArrayList<>();
//                mSupplyList = pubMatchData.get(position).getTitle();
//                if (0 != mSupplyList.size()){//评论的内容不为空
//                    rl_user.setVisibility(View.VISIBLE);
//                    if (mSupplyList.size() <= 1){
//                        user_a_ll.setVisibility(View.VISIBLE);
//                        user_b_ll.setVisibility(View.GONE);
//                        user_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getMember_no() + ": ");
//                        user_comment_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getContent());
//                    }else {
//                        user_a_ll.setVisibility(View.VISIBLE);
//                        user_b_ll.setVisibility(View.VISIBLE);
//                        user_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getMember_no() + ": ");
//                        user_comment_a.setText(mFindDataTwoList.get(position).getSupply().get(0).getContent());
//                        user_b.setText(mFindDataTwoList.get(position).getSupply().get(1).getMember_no() + ": ");
//                        user_comment_b.setText(mFindDataTwoList.get(position).getSupply().get(1).getContent());
//                    }
//                }else {
//                    rl_user.setVisibility(View.GONE);
//                }
                look_num_tv.setText(pubMatchData.get(position).getMember_no() + " 浏览");
                comment_num_tv.setText(pubMatchData.get(position).getRepeat() + " 评论");
//                collect_num_tv.setText(pubMatchData.get(position).getScore() + " 收藏");
                Glide.with(mActivity).load(pubMatchData.get(position).getMember_thumb()).into(store_logo_iv);
                store_name_tv.setText(pubMatchData.get(position).getMember_no());
                store_report_content.setText(pubMatchData.get(position).getTitle());
                report_time_tv.setText(pubMatchData.get(position).getCreate_time());
                get_message_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO: 2018/5/24 0024 查看信息
                        mActivity.MyToast("查看信息");
                    }
                });
                
                
                RecyclerView mRecyclerView = holder.getView(R.id.mRecyclerView);//图片的列表 3 列
                mRecyclerView.setLayoutManager(new GridLayoutManager(mActivity,3,GridLayoutManager.VERTICAL,false));
                BaseRVAdapter mPicAdapter = new BaseRVAdapter(mActivity,pubMatchData.get(position).getList_pic()) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_find_pic;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, final int position) {
                        ImageView find_pic_iv = holder.getImageView(R.id.find_pic_iv);
                        Glide.with(mActivity).load(pubMatchData.get(tagPosition).getList_pic().get(position)).into(find_pic_iv);
                        find_pic_iv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //点击查看大图
                                Intent intent = new Intent(mActivity,LookBigPicActivity.class);
                                intent.putExtra("imgUrl",pubMatchData.get(tagPosition).getList_pic().get(position));
                                intent.putExtra("listData", (Serializable) pubMatchData.get(tagPosition));
                                intent.putExtra("currentPosition",position);
                                startActivity(intent);
                            }
                        });
                    }

                };
                mRecyclerView.setAdapter(mPicAdapter);
                mPicAdapter.notifyDataSetChanged();
            }
        };
        
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(getActivity(),FindDetailActivity2.class);
                intent.putExtra("typeid",supply_cate_id);
                intent.putExtra("id",pubMatchData.get(position).getId());
                startActivity(intent);
            }
        });
        carListRecycler.setAdapter(mBaseAdapter);
        mBaseAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        if (page < last_page) {
            page ++;
            getDefaultFind();
        }else {
            mActivity.MyToast(getResources().getString(R.string.last_page));
            mRefreshLayout.finishLoadmore();
            mRefreshLayout.finishLoadmoreWithNoMoreData();
            return;
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        getDefaultFind();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != filterPopwindow){
            filterPopwindow.dismissView();
        }
    }
}
